var util = require('../../libs/util.js');
var app = getApp();
Page({
  data: {
    hasData: false,
    middle_height: "100vh",
    dd_style: "",
    warehouse: '全部',
    warehouseId: '',
    searchShowed: false,
    searchVal: "",
    pageSize: 20,
    pageNumber: 0,
    count: 0,
    page: 1,
    firstPage: true,
    prevPage: true,
    nextPage: true,
    lastPage: true
  },
  onPullDownRefresh: function () {
    //wx.stopPullDownRefresh()
  },
  onReady: function (e) {
  },
  onShow: function (e) {
    var that = this;
    wx.getStorage({
      key: 'monitor_warehouse',
      success: function (res) {
        if (res.data) {
          that.setData({
            warehouse: String(res.data.abbreviation || res.data.name).substr(0, 10),
            warehouseId: res.data.value
          })
        }
      },
      complete: function (res) {
        that.loadData();
        wx.removeStorage({
          key: 'monitor_warehouse',
          success: function (res) {
          }
        });
      }
    });
  },
  onLoad: function (e) {
    var that = this;
    wx.setNavigationBarTitle({ "title": app.appName +"--运力管理端" });
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          middle_height: res.windowHeight - 100,
          detail_height: res.windowHeight - 40
        });
      }
    });
    if (e.warehouseId) {
      that.setData({
        warehouse: e.warehouse,
        warehouseId: e.warehouseId
      });
    }
    that.setData({
      vehicleTag: util.vehicleTag
    })
    this.loadData();
  },
  onShareAppMessage: function () {
    return {
      title: app.appName +'-运力管理',
      path: '/pages/fleet/fleet?warehouse=' + this.data.warehouse + '&warehouseId=' + this.data.warehouseId
    }
  },
  showSearch: function () {
    this.setData({
      searchShowed: true
    });
  },
  hideSearch: function () {
    this.setData({
      searchVal: "",
      searchShowed: false
    });
    this.loadData();
  },
  clearSearch: function () {
    this.setData({
      searchVal: ""
    });
    this.loadData();
  },
  searchTyping: function (e) {
    this.setData({
      searchVal: e.detail.value
    });
    this.loadData();
  },
  loadData: function () {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    util.getData("/atapi/vehicle/vehicle/fleetManage", {
      warehouseId: that.data.warehouseId,
      CO_ID: app.globalData.CO_ID,
      sql: that.data.searchVal,
      'page': that.data.page,
      'pageSize': that.data.pageSize
    }, function (res, error) {
      console.log(res); console.log(error)
      if (res.data.success) {
        that.setData({
          hasData: true
        });
        var data = res.data.data[0], _data = [];
        for (var i = 0; i < data.length; i++) {
          _data.push({
            ID: data[i].ID,
            plate: data[i].plate,
            name: data[i].name || "未绑定",
            name2: data[i].name2 || "未绑定",
            bindDriver: (data[i].name ? true : false),
            bindDriver2: (data[i].name2 ? true : false),
            ischeck: (data[i].ischeck == '1' ? true : false),
            CO_NAME: (data[i].CO_ID == app.globalData.CO_ID ? '自有车辆' : data[i].CO_NAME) || '个人车辆',
            plate_owner: data[i].plate_owner || "无",
            carrier: data[i].carrier || "无",
            loadage: data[i].loadage || 0,
            driver_phone: data[i].driver_phone,
            driver_phone2: data[i].driver_phone2,
            vehicleFunction:data[i].vehicleFunction,
            vehicleSourceText:data[i].vehicleSourceText,
            semitrailer_plate:data[i].semitrailer_plate||'',
            semitrailer:data[i].semitrailer||'',
            tags: data[i].tags ? String(data[i].tags).split(",") : []
          });
        }
        var count = res.data.data[1][0].COUNT || 0;
        var pageNumber = Math.ceil(count / that.data.pageSize);
        that.setData({
          vehicleData: _data,
          count: count,
          pageNumber: pageNumber,
          page: that.data.page == 0 ? 1 : that.data.page
        })
        that.setPageStatus();
      } else {
        that.setData({
          hasData: false,
          vehicleData: [],
          page: 0,
          count: 0
        })
        that.setPageStatus();
      }
      wx.hideLoading();
    });
  },
  addTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var id = that.data.currentId;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length; i++) {
      if (vehicleData[i].ID == id) {
        var tagArray = vehicleData[i].tags;
        if (!tagArray) {
          tagArray = [];
          tagArray.push(tag);
          newtag = tagArray.join(",");
        } else {
          if (tagArray.indexOf(tag) > -1) {
            wx.showToast({
              title: '同名分类已存在',
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          } else {
            tagArray.push(tag);
            newtag = tagArray.join(",");
          }
        }
      }
    }
    that.setData({
      vehicleData: vehicleData,
      modalName: null
    });
    if (newtag) {
      that.saveNewTag(id, newtag);
    }
  },
  bindInput: function (e) {
    var item = String(e.currentTarget.id), item_value = {};
    item_value[item] = e.detail.value;
    this.setData(item_value);
  },
  addNewTag: function (e) {
    var that = this;
    var tag = that.data.newtag;
    if (!tag) {
      wx.showToast({
        title: '请输入标签名称',
        image: '/images/wrong.png',
        duration: 3000
      });
      return false;
    }
    var id = that.data.currentId;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length; i++) {
      if (vehicleData[i].ID == id) {
        var tagArray = vehicleData[i].tags;
        if (!tagArray) {
          tagArray = [];
          tagArray.push(tag);
          newtag = tagArray.join(",");
        } else {
          if (tagArray.indexOf(tag) > -1) {
            wx.showToast({
              title: '同名分类已存在',
              image: '/images/wrong.png',
              duration: 3000
            });
            return false;
          } else {
            tagArray.push(tag);
            newtag = tagArray.join(",");
          }
        }
        vehicleData[i].tags = tagArray;
        break;
      }
    }
    that.setData({
      vehicleData: vehicleData,
      modalName: null
    })
    if (newtag) {
      that.saveNewTag(id, newtag);
    }
  },
  saveNewTag: function (id, tags) {
    console.log(tags)
    util.postData("/atapi/vehicle/vehicle/saveVehicleTag", {
      id: id,
      tags: tags
    }, function (res, error) {
      if (res.data.success) {
        wx.showToast({
          title: '设置成功',
          icon: 'success',
          duration: 2000,
          success: function () {

          }
        })

      } else {
        wx.showToast({
          title: '设置失败',
          icon: 'success',
          duration: 2000
        })
      }
    });
  },
  deleteTag: function (e) {
    var that = this;
    var tag = e.currentTarget.dataset.tag;
    var id = e.currentTarget.dataset.id;
    var vehicleData = that.data.vehicleData;
    var newtag = '';
    for (var i = 0; i < vehicleData.length; i++) {
      if (vehicleData[i].ID == id) {
        var tags = vehicleData[i].tags;
        newtag = vehicleData[i].tags = util.arrayDeleteItem(vehicleData[i].tags, tag);
      }
    }
    if (newtag) {
      wx.showModal({
        title: '温馨提示',
        content: '确认要删除分类【' + tag + '】吗？',
        success(res) {
          if (res.confirm) {
            that.setData({
              vehicleData: vehicleData
            });
            that.saveNewTag(id, newtag);
          }
        }
      })
    }
  },
  vehicleTag: function (e) {
    var tag = e.currentTarget.dataset.tag;
    wx.navigateTo({
      url: '/pages/vehicle/vehicle_tag?tag=' + tag
    })
  },
  showModal(e) {
    var that = this;
    this.setData({
      modalName: e.currentTarget.dataset.target
    })

    if (e.currentTarget.dataset.target == 'tagModal') {
      that.setData({
        currentId: e.currentTarget.dataset.id
      })
    }
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  dispatch: function (e) {
    var id = e.currentTarget.id;
    wx.redirectTo({
      url: '/pages/fleet/vehicleBindWarehouse?id=' + id
    })
  },
  callDriver: function (e) {
    var phone = e.currentTarget.dataset.phone;
    if (phone) {
      wx.makePhoneCall({
        phoneNumber: phone
      })
    } else {
      wx.showToast({
        title: "暂无号码",
        image: '/images/wrong.svg',
        duration: 2000
      });
    }
  },
  //翻页按钮状态
  setPageStatus: function () {
    var that = this;
    var page = that.data.page, pageNumber = that.data.pageNumber;
    if (pageNumber == 1) {
      that.setData({
        firstPage: true,
        prevPage: true,
        nextPage: true,
        lastPage: true
      });
    } else if (pageNumber > 1) {
      if (page == 1) {
        that.setData({
          firstPage: true,
          prevPage: true,
          nextPage: false,
          lastPage: false
        });
      } else if (page == pageNumber) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: true,
          lastPage: true
        });
      } else if (page < pageNumber && page > 1) {
        that.setData({
          firstPage: false,
          prevPage: false,
          nextPage: false,
          lastPage: false
        });
      }
    }
  },
  //分页按钮操作
  pageChange: function (e) {
    var type = e.currentTarget.dataset.page;
    if (type == 'first') {
      this.setData({
        page: 1
      })
      this.loadData();
    }
    if (type == 'last') {
      this.setData({
        page: this.data.pageNumber
      })
      this.loadData();
    }
    if (type == 'prev') {
      this.setData({
        page: this.data.page - 1
      })
      this.loadData();
    }
    if (type == 'next') {
      this.setData({
        page: this.data.page + 1
      })
      this.loadData();
    }
  },
  changeDeliveryDate: function (e) {
    this.setData({
      delivery_date: e.detail.value,
      delivery_date_text: e.detail.value
    });
    this.loadData();
  },
  changeWarehouse: function (e) {
    var that = this;
    wx.navigateTo({
      url: '/pages/schedule/monitor_warehouse'
    })
  },
  gotoHome: function () {
    wx.navigateTo({
      url: '/pages/fleet/fleet'
    })
  },
  gotoVehicle: function () {
    wx.navigateTo({
      url: '/pages/fleet/vehicle'
    })
  },
  gotoSemitrailer: function () {
    wx.navigateTo({
      url: '/pages/vehicle/semitrailer'
    })
  },
  gotoDriver: function () {
    wx.navigateTo({
      url: '/pages/enterprise/user_driver?type=fleet'
    })
  },
  gotoInfo: function () {
    wx.navigateTo({
      url: '/pages/fleet/apps'
    })
  },
  gotoTransportCapacity:function(){
    wx.navigateTo({
      url: '/pages/vehicle/transport_capacity'
    })
  }
})
